package org.example.ai.controller;

import lombok.RequiredArgsConstructor;
import org.example.ai.repository.ChatHistoryRepository;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.content.Media;
import org.springframework.util.MimeType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("/ai")
@RequiredArgsConstructor
public class ChatController {
    private final ChatHistoryRepository chatHistoryRepository;
    private final ChatClient chatClient;
    @RequestMapping(value = "/chat",produces = "text/html;charset=utf-8")//produces设置响应结果类型
    public Flux<String> chat(@RequestParam("prompt") String prompt,
                             @RequestParam("prompt") String chatId,
                             @RequestParam(value = "files",required = false)List<MultipartFile> files){
        //保存会话Id
        chatHistoryRepository.save("chat",chatId);
        if(files==null || files.isEmpty()){
            return textchat(prompt,chatId);
        }else{
            return multModelsChat(prompt,chatId,files);
        }

    }

    private Flux<String> multModelsChat(String prompt, String chatId, List<MultipartFile> files) {
        List<Media> medias = files.stream().map(file -> new Media(MimeType.
                valueOf(file.getContentType()),
                file.getResource())).toList();


        //请求模型
        return chatClient.prompt()
                .user(p->p.text(prompt).media(medias.toArray(Media[]::new)))
                .advisors(a->a.param((ChatMemory.CONVERSATION_ID),chatId))
                .stream()
                .content();
    }

    private Flux<String> textchat(String prompt, String chatId) {
        //请求模型
        return chatClient.prompt()
                .user(prompt)
                .advisors(a->a.param((ChatMemory.CONVERSATION_ID),chatId))
                .stream()
                .content();
    }
}
